package wiki.kaizen.cloud.plugin.spring.scan.config;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import wiki.kaizen.cloud.plugin.spring.util.LocalTemporalUtil;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Set;

/**
 * string 日期 自动注入到 实体类 时间类型
 *
 * @author xeepoo
 * */
@Configuration
@AutoConfigureAfter(RequestMappingHandlerAdapter.class)
public class DateTimeAutoInjectConfig {


    private final GenericConversionService genericConversionService;

    public DateTimeAutoInjectConfig(GenericConversionService genericConversionService) {
        this.genericConversionService = genericConversionService;
    }

    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter(){
        //return LocalTemporalUtil::strToLocaDateTime;
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                return LocalTemporalUtil.strToLocaDateTime(source);
            }
        };
    }

    @Bean
    public Converter<String, LocalDate> localDateConverter(){
        //return LocalTemporalUtil::strToLocaDate;
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String source) {
                return LocalTemporalUtil.strToLocaDate(source);
            }
        };
    }

    @Bean
    public Converter<String, LocalTime> localTimeConverter(){
        //return LocalTemporalUtil::strToLocaTime;
        return new Converter<String, LocalTime>() {
            @Override
            public LocalTime convert(String source) {
                return LocalTemporalUtil.strToLocaTime(source);
            }
        };
    }

    @Bean
    public ConversionServiceFactoryBean conversionServiceFactoryBean(Set<Converter> converters){
        ConversionServiceFactoryBean factoryBean=new ConversionServiceFactoryBean();
        factoryBean.setConverters(converters);
        return factoryBean;
    }

    @PostConstruct
    public void setConverts(){
        genericConversionService.addConverter(localDateTimeConverter());
        genericConversionService.addConverter(localDateConverter());
        genericConversionService.addConverter(localTimeConverter());
    }
}
